package com.zc.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.dbutils.QueryRunner;

import com.zc.dao.DBPool;

public class JDBCUtils {

	private QueryRunner runner=new QueryRunner(DBPool.getInstance().getDataSource());
	/**
	 * 增加數據-返回更新數據id
	 * @param sql
	 * @param params
	 * @return
	 */
	public Long addObject(String sql,Object ...params) {
		Connection conn=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		try {
			conn=DBPool.getInstance().getConnection();
			pst=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			if(params!=null) {
				for(int i=0;i<params.length;i++) {
					pst.setObject(i+1,params[i]);
				}
			}
			pst.executeUpdate();
			//獲取主鍵
			rs=pst.getGeneratedKeys();
			return rs.next()?rs.getLong(1):-1;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			close(pst,conn,rs);
		}
		return 0l;
	}
	private void close(Statement st,Connection conn) {
		try {
			if(st!=null) {
				st.close();
			}
			if(conn!=null) {
				conn.close();
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	private void close(Statement st,Connection conn,ResultSet rs) {
		try {
			if(st!=null) {
				st.close();
			}
			if(conn!=null) {
				conn.close();
			}
			if(rs!=null) {
				conn.close();
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}
